<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { useUserInfoStore } from '@/stores/UserInfo.ts'
import { UserApi } from '@/api/UserApi.ts'
import type { UserVO, UpdateUserLoginParams } from '@/api/User.ts'

const router = useRouter()
const route = useRoute()
const userInfoStore = useUserInfoStore()
const originalUserInfo = ref<UserVO | null>(null)
const loading = ref(false)
const saving = ref(false)
const formRef = ref()

const userId = computed(() => {
  const paramId = route.params.userId
  const queryId = route.query.userId
  if (paramId && typeof paramId === 'string') {
    return paramId
  }
  if (queryId) {
    const id = Array.isArray(queryId) ? queryId[0] : queryId
    return typeof id === 'string' ? id : ''
  }
  return ''
})

const formData = ref<UpdateUserLoginParams>({
  userId: '',
  gender: 0,
  name: '',
  profile: '',
  email: ''
})

const formRules = ref({
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 4, max: 30, message: '昵称长度4-30位', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z\u4e00-\u9fa50-9_]+$/,
      message: '昵称只能包含字母、中文、数字和下划线',
      trigger: 'blur'
    }
  ],
  profile: [
    { max: 512, message: '简介长度不能超过512位', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
})

const genderOptions = [
  { label: '男', value: 0 },
  { label: '女', value: 1 }
]

const isCurrentUser = computed(() => {
  return userInfoStore.currentUser?.id === userId.value
})

const fetchUserInfo = async () => {
  if (!userId.value) {
    message.error('用户ID无效')
    await router.push('/personal')
    return
  }
  loading.value = true
  try {
    const userInfo = await userInfoStore.getUserInfo(userId.value)
    if (!userInfo) {
      message.error('用户信息不存在')
      await router.push('/personal')
      return
    }
    originalUserInfo.value = userInfo
    formData.value = {
      userId: userInfo.id,
      gender: userInfo.gender,
      name: userInfo.name,
      profile: userInfo.profile || '',
      email: userInfo.email || ''
    }
  } catch (error) {
    message.error('获取用户信息失败')
    await router.push('/personal')
  } finally {
    loading.value = false
  }
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    saving.value = true
    const success = await UserApi.updateLoginUser(formData.value)
    if (success) {
      message.success('保存成功')
      await userInfoStore.getUserInfo(userId.value)
      await router.push('/personal')
    } else {
      message.error('保存失败')
    }
  } catch (error) {
      message.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

const handleCancel = () => {
  router.push('/personal')
}

const handleReset = () => {
  if (originalUserInfo.value) {
    formData.value = {
      userId: originalUserInfo.value.id,
      gender: originalUserInfo.value.gender,
      name: originalUserInfo.value.name,
      profile: originalUserInfo.value.profile || '',
      email: originalUserInfo.value.email || ''
    }
    formRef.value?.clearValidate()
  }
}

const checkPermission = async () => {
  if (!userInfoStore.currentUser) {
    message.error('请先登录')
    await router.push('/login')
    return false
  }

  if (!isCurrentUser.value && !userInfoStore.isAdmin()) {
    message.error('无权限访问此页面')
    await router.push('/personal')
    return false
  }

  return true
}

onMounted(async () => {
  const hasPermission = await checkPermission()
  if (hasPermission) {
    await fetchUserInfo()
  }
})
</script>

<template>
  <div class="max-w-[800px] mx-auto p-4">
    <a-card>
      <template #title>
        <div class="flex items-center justify-between">
          <h1 class="text-2xl font-semibold text-gray-900 mb-0">编辑个人信息</h1>
          <a-space>
            <a-button @click="handleReset" :disabled="loading || saving">
              重置
            </a-button>
            <a-button @click="handleCancel" :disabled="loading || saving">
              取消
            </a-button>
          </a-space>
        </div>
      </template>

      <div v-if="loading" class="text-center py-8">
        <a-spin size="large">
          <div class="text-gray-500">加载中...</div>
        </a-spin>
      </div>

      <a-form
        ref="formRef"
        v-else
        :model="formData"
        :rules="formRules"
        layout="vertical"
        class="space-y-6"
      >
        <div class="border-b border-gray-200 pb-6">
          <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>

          <a-row :gutter="24">
            <a-col :xs="24" :md="12">
              <a-form-item label="昵称" name="name">
                <a-input
                  v-model:value="formData.name"
                  placeholder="请输入昵称"
                  :disabled="saving"
                />
              </a-form-item>
            </a-col>

            <a-col :xs="24" :md="12">
              <a-form-item label="性别" name="gender">
                <a-select
                  v-model:value="formData.gender"
                  :disabled="saving"
                >
                  <a-select-option
                    v-for="option in genderOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="邮箱" name="email">
            <a-input
              v-model:value="formData.email"
              type="email"
              placeholder="请输入邮箱地址"
              :disabled="saving"
            />
          </a-form-item>

          <a-form-item label="个人简介" name="profile">
            <a-textarea
              v-model:value="formData.profile"
              :rows="4"
              placeholder="请输入个人简介"
              :disabled="saving"
            />
          </a-form-item>
        </div>

        <div class="flex justify-end gap-3 pt-6">
          <a-button
            type="primary"
            @click="handleSave"
            :loading="saving"
            :disabled="loading"
          >
            {{ saving ? '保存中...' : '保存' }}
          </a-button>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<style scoped>
</style>
